<?php

namespace app\api\service;

use think\Controller;
use think\Db;
use Des3\DES3;
use think\Exception;

class Set extends Controller {

    /**
     * 获取设置验证数据
     * @param $param
     * @return array
     */
    public static function get_verification_info($param) {
        try {
            $member = model('member')->get(['id' => $param['member_id']]);
            $data['mobile'] = $member['username'];
            $data['mars_mobile'] = substr($member['username'], 0, 3) . '****' . substr($member['username'], -4);
            return api_return(200, $data);
        } catch (\Exception $e) {
            return api_return(0, [], $e->getMessage());
        }
    }

    // 设置安全密码
    public static function save_safe_password($param) {
        // 启动事务
        Db::startTrans();
        try {
            // 验证修改手机号码参数 是否提交完成
            $validate_set = validate('Set');
            $id = $param['member_id'];

            $member = model('member')->get(['id' => $id]);

            $des = new DES3();
            $safe_password = $des->decrypt($param['safe_password']);

            // 验证短信验证码是否有效
            $check_code = check_send_code($param['code'], $member['username']);
            if ($check_code['code'] != 200) {
                throw new \Exception($check_code['msg']);
            }

            // 验证安全密码格式
            if (!$validate_set->scene('safe_password')->check(['safe_password' => $safe_password])) {
                throw new \Exception('安全密码格式错误');
            }
            $safe_password  .= $member['salt'];
            $safe_password = md5($safe_password);
            model('member')->save(['safe_password' => $safe_password], ['id' => $id]);

            // 设置成功 清除错误记录（解锁）
            model('safe_password_error_log')->where('member_id', $param['member_id'])->delete();
            Db::commit();
            return api_return(200, []);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return api_return(0, [], $e->getMessage());
        }
    }

}